﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Primitives;
using SmartAgricultureService.Core;
using SmartAgricultureService.Models;

namespace SmartAgricultureService.Controllers
{
    public abstract class ControllerBase(IHttpContextAccessor httpContextAccessor) : Microsoft.AspNetCore.Mvc.ControllerBase
    {
        protected OkObjectResult Success<T>(T value)
        {
            var model = new AjaxResult<T>(value);
            return new OkObjectResult(model);
        }
        protected OkObjectResult Paging<T>(int index, int total, List<T> value, int size = 15)
        {
            var pagingResult = new PagingResult<T>(index, total, value, size);
            var model = new AjaxResult<PagingResult<T>>(pagingResult);
            return new OkObjectResult(model);
        }
        public OkObjectResult Success(string message)
        {
            var model = new AjaxResult<string>(message ?? string.Empty);
            return new OkObjectResult(model);
        }
        public BadRequestObjectResult Error(Exception exception)
        {
            Logger.Instance.LogError("Error", exception);
            var model = new AjaxResult<object>(exception);
            return new BadRequestObjectResult(model);
        }
        public BadRequestObjectResult Reject(string message = "")
        {
            var model = new AjaxResult<object>(message);
            return new BadRequestObjectResult(model);
        }
        public void SetHeader(string key, string value)
        {
            try
            {
                httpContextAccessor.HttpContext?.Response.Headers.TryAdd(key, value);
            }
            catch (Exception ex)
            {
                Logger.Instance.LogError("SetHeader", ex);
            }
        }
        public void GetHeader(string key, out string value, string defaultValue = "")
        {
            try
            {
                httpContextAccessor.HttpContext.Request.Headers.TryGetValue(key, out StringValues sv);
                value = sv.ToString().Replace("Bearer", "").Trim();
            }
            catch { value = string.Empty; }
            if (string.IsNullOrEmpty(value))
                value = defaultValue;
        }
    }
}